<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">湖南农大附近的零售货架</text>
    </view>
    
    <!-- 地图容器 -->
    <view class="map-container">
      <map
        id="map"
        class="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :circles="circles"
        scale="16"
        show-location="true"
        @markertap="onMarkerTap"
      ></map>
    </view>
    
    <!-- 底部信息栏 -->
    <view class="bottom-info">
      <view class="info-header">
        <text class="info-title">附近零售货架 ({{ markers.length - 1 }})</text>
        <text class="info-subtitle">显示1000米范围内的零售货架</text>
      </view>
      
      <scroll-view scroll-y class="shelf-list">
        <view 
          class="shelf-item" 
          v-for="(item, index) in shelfList" 
          :key="index"
          @click="navigateToShelf(item)"
        >
          <view class="shelf-icon">
            <uni-icons :type="item.icon" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="shelf-info">
            <text class="shelf-name">{{ item.name }}</text>
            <text class="shelf-address">{{ item.address }}</text>
            <view class="shelf-details">
              <text class="shelf-distance">距离 {{ item.distance }}米</text>
              <text class="shelf-status" :class="{ 'status-open': item.isOpen }">
                {{ item.isOpen ? '营业中' : '已关闭' }}
              </text>
            </view>
          </view>
          <view class="shelf-action">
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';

// 状态栏高度
const statusBarHeight = ref(0);

// 用户位置 - 湖南农业大学附近
const latitude = ref(28.1821);
const longitude = ref(113.0846);

// 零售货架数据（固定数据）- 湖南农业大学附近
const shelfData = ref([
  {
    id: 1,
    name: '校园零食站',
    latitude: 28.1841,
    longitude: 113.0866,
    address: '湖南农业大学学生公寓8栋附近',
    distance: 320,
    isOpen: true,
    icon: 'shop'
  },
  {
    id: 2,
    name: '24小时自助货架',
    latitude: 28.1801,
    longitude: 113.0826,
    address: '湖南农业大学图书馆附近',
    distance: 450,
    isOpen: true,
    icon: 'shop-filled'
  },
  {
    id: 3,
    name: '农大零食驿站',
    latitude: 28.1851,
    longitude: 113.0806,
    address: '湖南农业大学北门附近',
    distance: 680,
    isOpen: false,
    icon: 'cart'
  },
  {
    id: 4,
    name: '智能零售柜',
    latitude: 28.1791,
    longitude: 113.0876,
    address: '湖南农业大学东门附近',
    distance: 780,
    isOpen: true,
    icon: 'vip'
  },
  {
    id: 5,
    name: '校园便利站',
    latitude: 28.1871,
    longitude: 113.0836,
    address: '湖南农业大学体育馆附近',
    distance: 920,
    isOpen: true,
    icon: 'star'
  }
]);

// 计算地图标记点
const markers = computed(() => {
  // 用户位置标记
  const userMarker = {
    id: 0,
    latitude: latitude.value,
    longitude: longitude.value,
    iconPath: '/static/location.png', // 需要添加这个图标
    width: 30,
    height: 30,
    callout: {
      content: '当前位置',
      color: '#FF8C42',
      fontSize: 12,
      borderRadius: 4,
      padding: 5,
      display: 'ALWAYS'
    }
  };
  
  // 货架标记
  const shelfMarkers = shelfData.value.map(shelf => ({
    id: shelf.id,
    latitude: shelf.latitude,
    longitude: shelf.longitude,
    iconPath: shelf.isOpen ? '/static/shelf-open.png' : '/static/shelf-closed.png', // 需要添加这些图标
    width: 24,
    height: 24,
    callout: {
      content: shelf.name,
      color: '#333',
      fontSize: 12,
      borderRadius: 4,
      padding: 5,
      display: 'BYCLICK'
    }
  }));
  
  return [userMarker, ...shelfMarkers];
});

// 计算1000米范围圆圈
const circles = computed(() => [
  {
    latitude: latitude.value,
    longitude: longitude.value,
    color: '#FF8C4233', // 带透明度的颜色
    fillColor: '#FF8C4211', // 更透明的填充色
    radius: 1000,
    strokeWidth: 1
  }
]);

// 计算货架列表（按距离排序）
const shelfList = computed(() => {
  return [...shelfData.value].sort((a, b) => a.distance - b.distance);
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 点击标记点
const onMarkerTap = (e) => {
  const markerId = e.detail.markerId;
  if (markerId !== 0) { // 不是用户位置标记
    const shelf = shelfData.value.find(item => item.id === markerId);
    if (shelf) {
      uni.showToast({
        title: `已选择: ${shelf.name}`,
        icon: 'none'
      });
    }
  }
};

// 导航到货架详情
const navigateToShelf = (shelf) => {
  uni.showToast({
    title: `查看${shelf.name}详情`,
    icon: 'none'
  });
  // 这里可以添加导航到货架详情页的逻辑
  // uni.navigateTo({
  //   url: `/pages/shelf/detail?id=${shelf.id}`
  // });
};

// 获取用户位置
const getUserLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      console.log('获取位置成功:', res);
      latitude.value = res.latitude;
      longitude.value = res.longitude;
      
      // 更新货架距离（实际项目中应该根据经纬度计算真实距离）
      // 这里只是简单模拟
    },
    fail: (err) => {
      console.error('获取位置失败:', err);
      uni.showToast({
        title: '获取位置失败，使用默认位置',
        icon: 'none'
      });
    }
  });
};

// 接收页面参数
const onLoad = (options) => {
  if (options.shelfId) {
    console.log('打开指定货架:', options.shelfId);
    const shelfId = parseInt(options.shelfId);
    const shelf = shelfData.value.find(item => item.id === shelfId);
    
    if (shelf) {
      // 找到指定货架，将地图中心设为货架位置
      setTimeout(() => {
        uni.showToast({
          title: `已定位到: ${shelf.name}`,
          icon: 'none'
        });
        
        // 更新地图中心位置
        latitude.value = shelf.latitude;
        longitude.value = shelf.longitude;
      }, 500);
    }
  }
};

// 在onMounted中调用onLoad
onMounted(() => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 20;
  
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage && currentPage.options) {
    onLoad(currentPage.options);
  }
  
  // 获取用户位置
  getUserLocation();
});
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #FFF9F2;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  position: relative;
  z-index: 100;
}

.nav-back {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 80rpx; /* 为了标题居中 */
}

/* 地图容器 */
.map-container {
  flex: 1;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

/* 底部信息栏 */
.bottom-info {
  height: 40vh;
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  padding: 30rpx;
  position: relative;
  z-index: 10;
}

.info-header {
  margin-bottom: 20rpx;
}

.info-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.info-subtitle {
  font-size: 24rpx;
  color: #999;
}

.shelf-list {
  height: calc(40vh - 120rpx);
}

.shelf-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #FFE6CC;
}

.shelf-icon {
  width: 80rpx;
  height: 80rpx;
  background-color: #FFF0E0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.shelf-info {
  flex: 1;
}

.shelf-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 6rpx;
  display: block;
}

.shelf-address {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.shelf-details {
  display: flex;
  align-items: center;
}

.shelf-distance {
  font-size: 22rpx;
  color: #999;
  margin-right: 20rpx;
}

.shelf-status {
  font-size: 22rpx;
  color: #999;
}

.status-open {
  color: #FF8C42;
}

.shelf-action {
  padding: 0 10rpx;
}
</style>